/**
 * @description 实体-控制器
 * @since 2019-11-12
 * @author Rid King
*/

const fs = require("fs")
const { filer } = require('@daelui/oxkit')
const ox = require('@daelui/oxjs')
const Service = require('./service.js')

class Controller extends ox.Controller {
  /**
   * @function 构造方法
  */
  constructor (args) {
    super(args)
    // 服务
    this.$service = new Service(args)
  }

  /**
   * @function 增删改事件触发
  */
  emit (name, action, res) {
    super.emit(name, action, res)
    res = res || {}
    if (res.success && /insert/i.test(name)) {
      this.createTable(res, action)
      this.createAPI(res, action)
    }
  }

  /**
   * @function 创建表
  */
  async createTable (res, action) {
    let params = action.params
    // 查询微应用
    let mappRes = await this.$router.getControllInstance({path: '/tigerlair/mapp'}).query({}, {
      action: {},
      query: {},
      params: {
        id: params.mid
      }
    })
    // 字段
    let fields = []
    try {
      fields = JSON.parse(params.fields)
    } catch (e) {
      fields = []
    }
    // 表配置
    let db = this.route.scope.CONFIG.db
    let constant = this.route.scope.CONFIG.constant
    const tableName = params.code
    const DBClass = ox.dbFactory.getDBClass('json')
    // 应用路径
    let mappPath = constant.deployPath + '/' + mappRes.data.code
    let dbPath = mappPath + '/server/db'
    if (!fs.existsSync(dbPath)) {
      filer.buildPath(dbPath)
    }
    const dataSource = Object.assign({}, db, {
      table: this.table,
      define: dbPath
    })
    // 建立定义表
    const dbInstance = new DBClass(dataSource)
    dbInstance.defineTable({
      dataSource: dataSource,
      table: tableName,
      comment: params.name,
      fields: fields
    })
  }

  /**
   * @function 创建接口
  */
  async createAPI (res, action) {
    let params = action.params
    let eid = res.data || -1
    // 查询模板
    let dictRes = await this.$router.getControllInstance({path: '/tigerlair/dictionary'}).query({}, {
      action: {},
      query: {},
      params: {
        cat: 'api-tpl',
        status: '1'
      }
    })
    let dict = dictRes.data || {}
    if (!dict.id) {
      return false
    }
    dict.value = JSON.parse(dict.value)
    dict.volume = JSON.parse(dict.volume)
    // 添加的接口
    let inters = this.getInters({ entity: params.code, eid }, dict)
    // 查询所有的分组数据
    let result = await this.$router.getControllInstance({path: '/tigerlair/dapi'}).insertAll({}, {
      action: {},
      query: {},
      params: inters,
      excute: {}
    })

    if (result.data) {
      return {data: null, success: 1}
    }

    return {data: null, success: 0}
  }

  // 生成接口列表
  getInters ({ entity, eid }, dict) {
    let node = dict.volume
    // 接口模板
    let tplList = dict.value
    let inters = tplList.map(item => {
      let inter = { ...node }
      inter.eid = eid
      inter.code = item.value
      inter.name = item.text
      inter.url = dict.key.replace('{entity}', entity).replace('{action}', item.text)
      inter.method = item.method

      return inter
    })
    return inters
  }
}

module.exports = Controller